<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use DB;
use Mail;
use App\Http\Requests;
use App\Http\Requests\AdminLoginPostRequest;
use App\Http\Requests\HomeLoginPostRequest;
use App\Http\Controllers\Controller;

class LoginController extends Controller
{
    // 显示后台登录
    public function getLogin()
    {
        //显示模板
        return view('admin.login.login');

    }   

    //后台登录验证
    public function postCheck(AdminLoginPostRequest $request)
    {
       
        //根据用户名查询数据 检测用户是否存在
        $user = DB::table('trip_user')->where('username',$request->input('username'))->first();

        //用户名判断
        // if($user->username){
        //判断密码是否一致
           if(Hash::check($request->input('password'),$user->password)){
            // dd($user->auth);
                //判断权限
                if($user->auth == 2){
                //登录成功
                session(['id'=>$user->id]);
                session(['name'=>$user->username]);
                //跳转到后台页面
                return redirect('/admin')->with('success','欢迎登录');
            }else{
                return back()->with('error','用户权限不够');
            }

            }else{
                //失败
                return back()->with('error','用户名或者密码错误');
            }
        // }else{
        //  //失败
        //  return back()->with('error','用户名不存在');
        // }
    }

    //后台退出登录
    public function getLogout(){
        session()->forget('id','name');
        return redirect('/admin');
    }

    //前台登录
    public function HomeLogin()
    {
        //显示前台登录页面
        return view('home.login.login');
    }

    //前台登录验证
    public function doLogin(HomeLoginPostRequest $request)
    {
        // dd($request->all());
         //根据用户名查询数据 检测用户是否存在
        $user = DB::table('trip_user')->where('username',$request->input('username'))->first();
        // if($request->input('username') = $user->username){
        //判断密码是否一致
           if(Hash::check($request->input('password'),$user->password)){
                //登录成功
                session(['id'=>$user->id]);
                session(['name'=>$user->username]);
                //跳转到后台页面
                return redirect('/')->with('success','欢迎登录');
            }else{
                //失败
                return back()->with('error','用户名或者密码错误');
            }

    }

    //前台退出登录
    public function getOut()
    {
        session()->forget('id','name');
        return redirect('/');
    }

    //前台忘记密码
    public function Getpass()
    {
         //显示前台忘记密码页面
        return view('home.getpass.getpass');
    }

    //忘记密码验证
    public function doGetpass(Request $request)
    {
        $this->validate($request, [
        'password' => 'required',
        'repassword' => 'required|same:password',       
    ],[
        'password.required'=>'新密码不能为空',
        'repassword.required'=>'确认密码不能为空',
        'repassword.same'=>'两次密码不一致',

    ]);
        //获取输入的新密码
        $data = $request ->only('password');
        $data['password'] = Hash::make($data['password']);
        //根据用户查询
        // $user = DB::table('trip_user')->where('username',$request->input('username'))->first();
        //执行修改
        $res = DB::table('trip_user')->where('username',$request->input('username'))->update($data);
        //判断是否修改成功
        if($res){
            return redirect('/login')->with('success','密码修改成功');
        }else{
            return back()->with('error','密码修改失败');
        }
    } 

    //用户注册
    public function postInsert(Request $request)
    {
    	//所有数据
    	// dd($request->all());
    	//数据验证 自动闪存
    	$this->validate($request, [
        'username' => 'required|max:18',
        'username' => 'required|min:2',

        'password' => 'required',
        'repassword' => 'required|same:password',
 
        
    ],[
    	'username.required'=>'用户名不能为空',
    	'username.max'=>'用户名太长了',

    	'password.required'=>'用户密码不能为空',
    	'repassword.required'=>'确认密码不能为空',
    	'repassword.same'=>'两次密码不一致',

    ]);
    //验证成功 发送邮件
    //提取部分数据
    	$data = $request->only(['username','password','email']);
    	$data['token'] = str_random(50);
    	$data['password'] = Hash::make($data['password']);
        $data['status'] = 1;//未激活 2激活

    	//执行数据插入
    	$id = DB::table('trip_user')->insertGetId($data);
    	//判断是否添加成功
    	if($id){
            //注册成功后  发送邮件
            $this->sendMail($id,$data['token'],$data['email']);
            session(['name'=>$data['username']]);
    		return redirect('/')->with('success','注册成功');
    	}else{
    		return back()->with('error','注册失败,请联系管理员');
    	}
    }

        //发送邮件
    public function sendMail($id,$token,$email)
    {


        Mail::send('home.register.welcome', ['id'=>$id,'token'=>$token], function ($message)use($email) {
            $message->to($email)->subject('激活邮件');
            });
    }

    //激活账号
    public function jihuo(Request $request)
    {
        //dd($request->all());
        $id = $request->input('id');
        //根据用户id查询用户是否存在
        $user = DB::table('trip_user')->where('id',$id)->first();
        //请求token是否正确
        if($user->token == $request->input('token')){
            //都正确后修改为 激活状态  
            $data['status'] = 2;
            //生成新token
            $data['token'] = str_random(50);
            //执行修改
            $res = DB::table('trip_user')->where('id',$id)->update($data);
            if($res){
                echo '激活成功';
                return redirect('/');
            }else{
                echo '激活失败';
            }
        }else{
            echo '链接失效';
        }
    }

    //注册时查询用户名是否已存在
    public function getSamename(Request $request)
    {
         // dd($request->all());
         //根据用户名查询数据 检测用户是否存在
        $user = DB::table('trip_user')->where('username',$request->input('username'))->first();
        if(empty($user)){
            echo 1;
        }

    }


        //判断验证码是否正确
        public function getVccoo(Request $request)
        {
            $res = $request->only('codename');
                 
             if($res['codename'] != session('code')){
                echo 2;
             }
             else{
                echo 1;
             }
        }

        //生成验证码
        public function getVcode()
        {  
            $code = self::yzm(80,30,4,2);
            session(['code'=>$code]);
        }


        //验证码函数
        public static function yzm($width = 100,$height = 30,$len = 4,$type = 1){
        //画验证码
        //1.创建画布 
        $res = imagecreatetruecolor($width,$height);

        //2.准备颜色 rand  值越小 颜色越深 值越大颜色越浅
        //浅颜色
        $qian = imagecolorallocate($res,rand(140,255),rand(130,200),rand(150,240));

        //深颜色
        $dark = imagecolorallocate($res,rand(0,100),rand(30,120),rand(20,140));

        //3.开始绘画
        imagefilledrectangle($res,0,0,$width,$height,$qian);

        //画字符
        //imagettftext ( resource $image , float $size , float $angle , int $x , int $y , int $color , string $fontfile , string $text )
        switch($type){
            case 1:
                $str = implode('',array_rand(array_flip(array_merge(range('a','z'),range('A','Z'))),$len));
                break;
            case 2:
                $str = implode('',array_rand(array_flip(range('1','9')),$len));
                break;
        }
        
        
        
        for($i = 0;$i < $len;$i++){
            imagettftext($res,14,rand(-30,30),rand($i*($width/$len),(($i+1)*($width/$len)-5)),rand(12,$height),$dark,'public/home/simhei.ttf',$str{$i});
        }

        //干扰元素  线  点
        for($i = 1;$i < 6;$i++){
            imageline($res,rand(0,$width),rand(0,$height),rand(0,$width),rand(0,$height),$dark);
        }

        for($i = 1;$i <= 100;$i++){
            imagesetpixel($res,rand(0,$width),rand(0,$height),$dark);
        }

        //4.告诉浏览器这是一个图像
        header('Content-type:image/jpeg');

        // //5.将图像输出给浏览器
        imagejpeg($res);

        // //6.销毁资源
        imagedestroy($res);
        
        return $str;
    }




}
